export default {
  methods: {
    /**
     * 登录
     */
    login(username, password) {
      return new Promise((resolve, reject) => {
        let options = {
          apiUrl: this.$WebIM.config.apiURL,
          user: username,
          pwd: password,
          appKey: this.$WebIM.config.appkey,
          success: resp => {
            this.setCurrentUser(resp, password);
            resolve(resp);
          },
          error: err => {
            reject(err);
          }
        };

        this.$imConn.open(options);
      });
    },
    register(params) {
      return new Promise((resolve, reject) => {
        let options = {
          ...params,
          appKey: this.$WebIM.config.appkey,
          apiUrl: this.$WebIM.config.apiURL,
          success: resp => {
            resolve(resp);
          },
          error: err => {
            reject(err);
          }
        };
        this.$imConn.registerUser(options);
      });
    },

    // 更新本地用户信息
    setCurrentUser(res, pwd) {
      this.$currentUser = res;
      let token = res.access_token;
      //存储token到本地 方便二次登陆
      this.$WebIM.utils.setCookie("webim_token", token, 1);
      this.$WebIM.utils.setCookie("webim_user", JSON.stringify(res.user), 1);
      this.$WebIM.utils.setCookie("webim_pwd", pwd, 1);
    },

    /**
     * 验证登录状态
     */
    validateLogin() {
      return new Promise((resolve, reject) => {
        if (this.$currentUser.access_token != undefined) {
          resolve(this.$currentUser);
          return;
        }
        const {
          webim_user,
          webim_pwd,
          webim_token
        } = this.$WebIM.utils.getCookie();
        const currentUser = JSON.parse(webim_user);
        if (webim_token == undefined) {
          //跳出登录
          reject();
          return;
        }

        //重新登陆
        let options = {
          apiUrl: this.$WebIM.config.apiURL,
          user: currentUser.username,
          // accessToken: cookieToken,
          pwd: webim_pwd,
          appKey: this.$WebIM.config.appkey,
          success: res => {
            this.setCurrentUser(res, webim_pwd);
            resolve(res);
          },
          error: () => {
            alert("登陆发生异常");
          }
        };
        this.$imConn.open(options);
      });
    },
    //退出
    logout() {
      this.$imConn.close();
    },

    getGroup() {
      return new Promise((resolve, reject) => {
        let options = {
          success: resp => {
            console.log("Response: ", resp);
            resolve(resp);
          },
          error: e => {
            reject(e);
          }
        };
        this.$imConn.getGroup(options);
      });
    },

    listGroupMember(groupid) {
      return new Promise((resolve, reject) => {
        let pageNum = 1;
        let pageSize = 1000;
        let options = {
          pageNum: pageNum, // 页码
          pageSize: pageSize, // 预期每页获取的记录数
          groupId: groupid,
          success: resp => {
            console.log("Response: ", resp);
            resolve(resp);
          },
          error: e => {
            reject(e);
          }
        };
        this.$imConn.listGroupMember(options);
      });
    },
    sendPrivate(uname, msgCon) {
      return new Promise((resolve, reject) => {
        let id = this.$imConn.getUniqueId(); // 生成本地消息id
        let msg = new this.$WebIM.message("txt", id); // 创建文本消息
        const { webim_user } = this.$WebIM.utils.getCookie();
        const currentUser = JSON.parse(webim_user);
        let options = {
          msg: msgCon,
          to: uname,
          roomType: false,
          success: (id, serverMsgId) => {
            console.log("send private text Success");
            resolve({
              id: serverMsgId,
              type: "groupchat",
              from: currentUser.username,
              to: uname,
              data: msgCon,
              ext: {}
            });
          }, // 对成功的相关定义，sdk会将消息id登记到日志进行备份处理
          fail: err => {
            console.log("Send private text error");
            reject(err);
          } // 对失败的相关定义，sdk会将消息id登记到日志进行备份处理
        };
        msg.set(options);
        this.$imConn.send(msg.body);
      });
    },
    /**
     * 给群组发送消息
     */
    sendMsgToGroup(uname, groupid, msgCon) {
      return new Promise((resolve, reject) => {
        let id = this.$imConn.getUniqueId(); // 生成本地消息id
        let msg = new this.$WebIM.message("txt", id); // 创建文本消息
        let option = {
          msg: msgCon, // 消息内容
          to: groupid, // 接收消息对象(群组id)
          roomType: false, // 群聊类型，true时为聊天室，false时为群组
          success: (id, serverMsgId) => {
            console.log("send room text success");
            resolve({
              id: serverMsgId,
              type: "groupchat",
              from: uname,
              to: groupid,
              data: msgCon,
              ext: {},
              head: ""
            });
          }, // 对成功的相关定义，sdk会将消息id登记到日志进行备份处理
          fail: err => {
            console.log("failed");
            reject(err);
          } // 对失败的相关定义，sdk会将消息id登记到日志进行备份处理
        };
        msg.set(option);
        msg.setGroup("groupchat");
        this.$imConn.send(msg.body);
      });
    }
  },
  // 聊天室发送文本消息
  sendRoom(msgCon, roomId) {
    return new Promise((resolve, reject) => {
      var id = this.$imConn.getUniqueId(); // 生成本地消息id
      var msg = new this.$WebIM.message("txt", id); // 创建文本消息
      var option = {
        msg: msgCon, // 消息内容
        to: roomId, // 接收消息对象(聊天室id)
        roomType: true,
        chatType: "chatRoom",
        success: resp => {
          console.log("send room text success");
          resolve(resp);
        },
        fail: err => {
          console.log("failed");
          reject(err);
        }
      };
      msg.set(option);
      msg.setGroup("groupchat");
      this.$imConn.send(msg.body);
    });
  },
  /**
   * 获取对话历史消息
   * @param {String} options.queue   - 对方用户名Id
   * @param {String} options.count   - 每次拉取条数
   */
  fetchHistoryMessages(queue, count = 10) {
    return new Promise((resolve, reject) => {
      let options = {
        queue,
        count,
        success: resp => {
          resolve(resp);
        },
        fail: err => {
          reject(err);
        }
      };
      this.$imConn.fetchHistoryMessages(options);
    });
  }
};
